package com.hcy.rabbitbasicutils.utils;

import com.hcy.rabbitbasicmodel.enums.Code;
import com.hcy.rabbitbasicmodel.model.ResponseData;
import com.hcy.rabbitbasicmodel.model.ReturnResult;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.awt.*;
import java.util.List;
import java.util.Map;

/**
 * @Author huchenying
 * @Description
 * @Date 2021/12/21 15:01
 */
@Component
public class MyHttpUtils {

    Logger logger = LoggerFactory.getLogger(MyHttpUtils.class);
    @Autowired
    private RestTemplate restTemplate;

    public ReturnResult sendPostRequest(String url, MultiValueMap<String, Object> params,MultiValueMap<String, String> header) {
        HttpHeaders headers = new HttpHeaders();
        headers.addAll(header);
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //将请求头部和参数合成一个请求
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求，将返回的结构使用Result类格式化
        ResponseEntity<Object> response = restTemplate.exchange(url, method, requestEntity, Object.class);
        logger.info("res - > [{}]", ToStringBuilder.reflectionToString(response));
        if (response.getStatusCode() == HttpStatus.OK) {
            return ReturnResult.success().setData(response.getBody());
        }
        if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            ReturnResult result = new ReturnResult();
            result.setCode(Code.UNAUTH);
            result.setMsg("未认证！");
            return result;
        }
        return ReturnResult.fail("请求失败！");
    }

    public ResponseData<Object> sendGetRequest(String url,Map<String,Object> params) {
        ResponseData<Object> responseData = new ResponseData<>();
        url = expendUrl(url,params);
        try {
            //执行HTTP请求，将返回的结构使用Result类格式化
            Object  response = restTemplate.getForObject(url, Object.class);
            responseData.setCode(Code.Success);
            responseData.setData(response);
            return responseData;
        } catch (RestClientException e) {
            e.printStackTrace();
            responseData.setCode(Code.Fail);
            responseData.setMsg(e.getMessage());
            return responseData;
        }
    }

    public String expendUrl(String url,Map<String,Object> params){
        StringBuilder sb = new StringBuilder();
        sb.append(url).append("?");
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        if(params.size() > 0){
            sb.deleteCharAt(sb.lastIndexOf("&"));
        }
        return sb.toString();
    }

    /**
     * @Author huchenying
     * @Description 检验token是否还生效
     * @Date 2022/3/14 13:48
     **/
}
